package org.thanos.demo.config;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

import static org.thanos.demo.constants.DynamicTaskConstants.*;

public class DynamicTaskConsumeThreadFactory implements ThreadFactory {

    private static final AtomicInteger poolNumber = new AtomicInteger(1);
    private final ThreadPoolExecutor executorPool;
    private final AtomicInteger threadNumber = new AtomicInteger(1);
    private final String namePrefix;

    public DynamicTaskConsumeThreadFactory() {
        super();
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        executorPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAXIMUM_POOL_SIZE, 1, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(WORK_QUEUE_CAPACITY), threadFactory);
        namePrefix = "pool-" +
                poolNumber.getAndIncrement() +
                "-dynamic-task-";
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread t = executorPool.getThreadFactory().newThread(r);
        t.setName(namePrefix + threadNumber.getAndIncrement());
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}
